﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Mal.Balades.Admin.Services;
using Mal.Balades.Admin.ViewModels.VisitViewModels.Edit.Data;

namespace Mal.Balades.Admin.ViewModels.VisitViewModels.Edit
{
    public class VisitEditViewModel : PageViewModelBase
    {
        #region Fields
        IAdminService service;

        VisitViewModel sourceVisit;

        private bool isLoading;
        private bool isVisitLoading;
        private bool isPicturesLoading;
        private bool isInformationsLoading;
        private bool isSaving;

        private List<ITabItemViewModel> tabs;
        private TabViewModelBase selectedTab;
        private int selectedTabIndex = -1;

        private RelayCommand saveCommand;
        private RelayCommand addCommand;

        #endregion

        #region Construction / Destruction
        public VisitEditViewModel()
            //: base(mainViewModel)
        {
            this.service = AdminServiceFactory.GetInstance();
            this.service.GetVisitCompleted += new ServiceResponse<IVisitAdmin>(OnGetVisitCompleted);
            this.service.GetVisitInformationsCompleted += new ServiceResponse<ReadOnlyCollection<IInformation>>(OnGetVisitInformationsCompleted);
            this.service.GetVisitPicturesCompleted += new ServiceResponse<ReadOnlyCollection<IPicture>>(OnGetVisitPicturesCompleted);
            this.service.SaveVisitCompleted += new ServiceResponse<ISaveVisitResult>(OnSaveVisitCompleted);
        }

       


        #endregion

        #region enum, struct, class

        #endregion

        #region Properties
        public bool IsLoading
        {
            get { return isLoading; }
            set
            {
                if (isLoading != value)
                {
                    isLoading = value;
                    RaisePropertyChanged("IsLoading");
                }

                if (isLoading)
                {
                    Messenger.Default.Send<MainViewModel.MessageBarMessage>(
                            new MainViewModel.MessageBarMessage(this,"Chargement de la visite en cours ...."));
                }
                else
                {
                    Messenger.Default.Send<MainViewModel.MessageBarMessage>(
                            new MainViewModel.MessageBarMessage(this));
                }
            }
        }

        public bool IsSaving
        {
            get { return isSaving; }
            set
            {
                if (isSaving != value)
                {
                    isSaving = value;
                    RaisePropertyChanged("IsSaving");
                    SetIsLoading();

                    if (isSaving)
                    {
                         Messenger.Default.Send<MainViewModel.MessageBarMessage>(
                            new MainViewModel.MessageBarMessage(this, "Sauvegarde de la visite en cours ...."));
                    }
                    else
                    {
                         Messenger.Default.Send<MainViewModel.MessageBarMessage>(
                            new MainViewModel.MessageBarMessage(this));
                    }
                }
            }
        }

        public bool IsVisitLoading
        {
            get { return isVisitLoading; }
            set
            {
                if (isVisitLoading != value)
                {
                    isVisitLoading = value;
                    RaisePropertyChanged("IsVisitLoading");
                    SetIsLoading();
                }
            }
        }

        public bool IsInformationsLoading
        {
            get { return isInformationsLoading; }
            set
            {
                if (isInformationsLoading != value)
                {
                    isInformationsLoading = value;
                    RaisePropertyChanged("IsInformationsLoading");
                    SetIsLoading();
                }
            }
        }

        public bool IsPicturesLoading
        {
            get { return isPicturesLoading; }
            set
            {
                if (isPicturesLoading != value)
                {
                    isPicturesLoading = value;
                    RaisePropertyChanged("IsPicturesLoading");
                    SetIsLoading();
                }
            }
        }

        public VisitViewModel SourceVisit
        {
            get { return sourceVisit; }
            set
            {
                sourceVisit = value;
                RaisePropertyChanged("SourceVisit");

                BuildTabs();
            }
        }

        public int SelectedTabIndex
        {
            get { return selectedTabIndex; }
            set
            {
                if (selectedTabIndex != value)
                {
                    selectedTabIndex = value;
                    RaisePropertyChanged("SelectedTabIndex");

                    this.SelectedTab = (TabViewModelBase)this.Tabs[selectedTabIndex];
                }
            }
        }

        public TabViewModelBase SelectedTab
        {
            get { return selectedTab; }
            set
            {
                if (selectedTab != value)
                {
                    selectedTab = value;
                    RaisePropertyChanged("SelectedTab");
                }
            }
        }

        public List<ITabItemViewModel> Tabs
        {
            get { return tabs; }
            set
            {
                if (tabs != value)
                {
                    tabs = value;
                    RaisePropertyChanged("Tabs");
                }
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                if (this.saveCommand == null)
                {
                    this.saveCommand = new RelayCommand(OnSave);
                }
                return this.saveCommand;
            }
        }

        public ICommand AddCommand
        {
            get
            {
                if (this.addCommand == null)
                {
                    this.addCommand = new RelayCommand(OnAdd/*,CanAdd*/);
                }
                return this.addCommand;
            }
        }

        #endregion

        #region Methods
        public override void Cleanup()
        {
            if (this.service != null)
            {
                this.service.GetVisitCompleted -= new ServiceResponse<IVisitAdmin>(OnGetVisitCompleted);
                this.service.GetVisitInformationsCompleted -= new ServiceResponse<ReadOnlyCollection<IInformation>>(OnGetVisitInformationsCompleted);
                this.service.GetVisitPicturesCompleted -= new ServiceResponse<ReadOnlyCollection<IPicture>>(OnGetVisitPicturesCompleted);
                this.service.SaveVisitCompleted -= new ServiceResponse<ISaveVisitResult>(OnSaveVisitCompleted);

                this.service.Cleanup();
                this.service = null;
            }
            base.Cleanup();
        }

        private void LoadVisit(int visitId)
        {
            this.IsVisitLoading = true;
            this.IsInformationsLoading = true;
            this.IsPicturesLoading = true;

            this.service.GetVisitAsync(visitId);
           
        }

        private void SetIsLoading()
        {
            this.IsLoading = this.isPicturesLoading || this.isVisitLoading || this.isInformationsLoading || this.isSaving;
        }

        private void BuildTabs()
        {
            this.Tabs.Add(new MainTabViewModel(this));
            this.Tabs.Add(new InformationsTabViewModel(this));
            this.Tabs.Add(new PicturesTabViewModel(this));
            this.Tabs.Add(new MapTabViewModel(this));

            this.SelectedTabIndex = 0;

            RaisePropertyChanged("Tabs");
        }

        protected void OnSave()
        {
            this.IsSaving = true;
            if (this.SourceVisit.VisitID != 0)
            {
                SaveVisitObject saveVisitObject = new SaveVisitObject();

                saveVisitObject.Visit.Latitude = this.SourceVisit.Latitude;
                saveVisitObject.Visit.Longitude = this.SourceVisit.Longitude;
                saveVisitObject.Visit.MarketingCategoryID = this.SourceVisit.MarketingCategoryID;
                saveVisitObject.Visit.PlaceCategoryID = this.SourceVisit.PlaceCategoryID;
                saveVisitObject.Visit.QualityCategories = this.SourceVisit.QualityCategories;
                saveVisitObject.Visit.QualityGps = this.SourceVisit.QualityGps;
                saveVisitObject.Visit.QualityInformations = this.SourceVisit.QualityInformations;
                saveVisitObject.Visit.QualityPictures = this.SourceVisit.QualityPictures;
                saveVisitObject.Visit.QualitySumUp = this.SourceVisit.QualitySumUp;
                saveVisitObject.Visit.QualityText = this.SourceVisit.QualityText;
                saveVisitObject.Visit.SumUp = this.SourceVisit.SumUp;
                saveVisitObject.Visit.Text = this.SourceVisit.Text;
                saveVisitObject.Visit.Title = this.SourceVisit.Title;
                saveVisitObject.Visit.UrlName = this.SourceVisit.UrlName;
                saveVisitObject.Visit.Visible = this.SourceVisit.Visible;
                saveVisitObject.Visit.VisitID = this.SourceVisit.VisitID;

                foreach (PictureViewModel picture in this.SourceVisit.Pictures)
                {
                    Picture pictureSave = new Picture();
                    pictureSave.PictureID = picture.PictureID;
                    pictureSave.PictureTypeID = picture.PictureTypeID;
                    pictureSave.Rank = picture.Rank;
                    pictureSave.Text = picture.Text;
                    pictureSave.Title = picture.Title;
                    pictureSave.Url = picture.Url;
                    pictureSave.VisitID = picture.VisitID;
                    saveVisitObject.AddPicture(pictureSave);
                }

                foreach (InformationViewModel information in this.SourceVisit.Informations)
                {
                    Information informationSave = new Information();
                    informationSave.InformationID = information.InformationID;
                    informationSave.InformationTypeID = information.InformationTypeID;
                    informationSave.Rank = information.Rank;
                    informationSave.Text = information.Text;
                    informationSave.VisitID = information.VisitID;

                    saveVisitObject.AddInformation(informationSave);
                }

                this.service.SaveVisitAsync(saveVisitObject);            
            }
        }

        protected void OnAdd()
        {
            if (this.SelectedTab != null)
            {
                this.SelectedTab.Add();
            }
        }

        //protected bool CanAdd()
        //{
        //    if (this.selectedTab != null)
        //    {
        //        return ((TabViewModelBase)this.selectedTab).AddCommandEnabled;
        //    }

        //    return false;
        //}

        #endregion

        #region Events
        void OnGetVisitCompleted(ServiceResponseArgs<IVisitAdmin> e)
        {
            this.IsVisitLoading = false;

            if (e.Error != null)
                throw e.Error;

            this.SourceVisit = new VisitViewModel(e.Result);
            this.service.GetVisitPicturesAsync(this.SourceVisit.VisitID.Value);
            this.service.GetVisitInformationsAsync(this.SourceVisit.VisitID.Value);
        }

        void OnGetVisitPicturesCompleted(ServiceResponseArgs<ReadOnlyCollection<IPicture>> e)
        {

            this.IsPicturesLoading = false;
            if (e.Error != null)
                throw e.Error;

            foreach (IPicture picture in e.Result)
            {
                this.SourceVisit.Pictures.Add(new PictureViewModel(picture));
            }
        }

        void OnGetVisitInformationsCompleted(ServiceResponseArgs<System.Collections.ObjectModel.ReadOnlyCollection<IInformation>> e)
        {
            this.IsInformationsLoading = false;
            if (e.Error != null)
                throw e.Error;

            foreach (IInformation info in e.Result)
            {
                this.SourceVisit.Informations.Add(new InformationViewModel(info));
            }
        }

        void OnSaveVisitCompleted(ServiceResponseArgs<ISaveVisitResult> e)
        {
            this.IsSaving = false;
            if (e.Error != null)
                throw e.Error;

            
        }

        public override void OnNavigate()
        {

            this.Tabs = new List<ITabItemViewModel>();
            bool createNewVisit = true;
            if (this.NavigationContext.QueryString.ContainsKey("visitId"))
            {
                int visitId = 0;
                if (int.TryParse(this.NavigationContext.QueryString["visitId"], out visitId))
                {
                    if (visitId > 0)
                    {
                        createNewVisit = false;
                        LoadVisit(visitId);
                    }
                }
            }

            if (createNewVisit)
            {
                this.SourceVisit = new VisitViewModel();
            }

        }
        #endregion
    }
}
